#!/bin/sh
#desc:Changes the next song as the current
#package:odbgmusic
#type:local

CONFILE=/etc/opendomo/music.conf
. $CONFILE
. $PID

# Check random mode

if test "$RDM" == off; then

	# Check there are songs in pending
	if test "" != "`cat $TMPPENDING`"; then

		# Move song from current to the end of played
        	if test "" = "`cat $TMPPLAYED`"; then
                	echo "`cat $TMPCURRENT`"        > $TMPPLAYED
	        else
	                echo "`cat $TMPCURRENT`"        >> $TMPPLAYED
		fi

	        # Move the first song of pending to current
        	echo "`cat $TMPPENDING |grep -m 1 $`"   >$TMPCURRENT

	        # Erase the first song of pending
        	echo "`sed '1d' $TMPPENDING`" > $TMPPENDING
	else
        	echo "#INFO No pending songs to be played"
		if test "0" = "`tail -n1 $INFFILE  | cut -f2 -d" "`" && test "@P" = "`tail -n1 $INFFILE  | cut -f1 -d" "`"; then
        		echo "`sed '1d' $TMPCURRENT`" > $TMPCURRENT                                                         
        	fi	
	fi
else

	# Check there are songs in pending in random mode
	if test "" != "`cat $TMPPENDING`"; then
        
		# Send song from current to played

	        if test "" = "`cat $TMPPLAYED`"; then	
	                echo "`cat $TMPCURRENT`"        > $TMPPLAYED
	        else
       		        echo "`cat $TMPCURRENT`"        >> $TMPPLAYED
		fi

        	# Get the number of pending songs
	        pending=`wc -l $TMPPENDING | cut -d" " -f1`

	        # Get the number of song
        	item=$(($RANDOM%$pending+1))

       	 	# Set the song as current
        	echo "`cat $TMPPENDING | sed -n ''$item'p'`"   >$TMPCURRENT

        	# Remove the song from pending
        	echo "`sed ''$item'd' $TMPPENDING`" > $TMPPENDING
	else
        	echo "#INFO No pending songs to be played"
        	if test "0" = "`tail -n1 $INFFILE  | cut -f2 -d" "`" && test "@P" = "`tail -n1 $INFFILE  | cut -f1 -d" "`"; then
                	echo "`sed '1d' $TMPCURRENT`" > $TMPCURRENT
        	fi
	fi

fi

# Always return to bgmusic web controler

/usr/local/opendomo/bgmusicControl.sh

